package com.test.socket;

import java.io.IOException; 
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;



public class UDPTimeServer extends Thread {
	
    final private static int DAYTIME_PORT = 7897;

    private DatagramSocket serverSocket = null;

    private final int THREAD_POOL = 10;

    private ExecutorService threadPool = null;

    public UDPTimeServer() throws IOException {
        serverSocket = new DatagramSocket(DAYTIME_PORT);
        threadPool = Executors.newFixedThreadPool(THREAD_POOL);
        
        System.out.println("时间服务器启动成功,监听端口 [" 
        		+ DAYTIME_PORT + "] 线程池 ["+ THREAD_POOL + "]...");
    }

    public void run() {
        while (true) {
            try {
                byte buffer[] = new byte[256];
                DatagramPacket packet = new DatagramPacket(buffer,buffer.length);
                serverSocket.receive(packet);
               
                System.out.println("收到客户端 [" + packet.getSocketAddress()
                        + " ] 请求");
                
                threadPool.execute(new HandlerThread(packet));
            } catch (Exception e) {
            	
            }
        }
    }

  
    private class HandlerThread extends Thread {
        private DatagramPacket packet = null;

        public HandlerThread(DatagramPacket p) {
            packet = p;            
        }
        public void run() {
        	if(handlePacket()>0)
        	  sendPacket();
        }
        private int handlePacket(){
        	byte[]data =packet.getData();
        	int len = packet.getLength();
        	//String str = new String(data,0,len);
           try{
        	   String str = new String(data,0,len,"UTF-8");
        	   System.out.println(str);
           }catch(Exception	e)
           { System.out.println(e);}
        	
        	return 1;
        }
        
        private void sendPacket()
        {
        	try {
            	
                String date = new Date().toString();
                date+="请求单个中文字";
               // 发送UTF-8数据流
                byte[] buffer = date.getBytes("UTF-8");

                InetAddress address = packet.getAddress();
                int port = packet.getPort();
                packet = new DatagramPacket(buffer, buffer.length, address, port);
                serverSocket.send(packet);

                System.out.println("线程 [" + getName() + "] 向客户端 ["
                        + packet.getSocketAddress() + " ]  发送数据");
                      
            } catch (Exception e) {

            } finally {
                packet = null;
            }
        
        	
        }
       
    }

    public static void main(String args[]) throws IOException {
        new UDPTimeServer().start();
    }
}

